package com.pz.cloud.framework.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.pz.cloud.framework.model.ThreadTask;
import org.jeecg.common.model.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.*;

/**
 * 3hmzz 线程任务工具类
 */
public class ThreadTaskUtil {
    private  static final Logger log = LoggerFactory.getLogger(ThreadTaskUtil.class);
    private static final int TIME = 30;

    private static final int QUEUE_SIZE = 5000;

    private static final int CORE_POOL_SIZE = 15;

    private static final int MAXIMUM_POOL_SIZE = 15;

    private static ThreadFactory namedThreadFactory;

    private static ExecutorService singleThreadPool;


    static {
        namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("needSetValueAspect-pool-%d").build();
    }

    public static ExecutorService getThreadPool(){
        if(singleThreadPool==null){
             singleThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
                    TIME, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
        }
        return  singleThreadPool;
    }
    /**
     * 多任务执行 开启多个线程
     * @param executeBeans
     * @param callable
     * @param <T>
     */
    public static <T>void excute(List<T> executeBeans, Callable callable){
        CountDownLatch countDown = new CountDownLatch(executeBeans.size());//线程计数器
        ExecutorService singleThreadPool = getThreadPool();
        executeBeans.forEach(b->
            submit(singleThreadPool,new ThreadTask(callable,b,countDown))
        );
        try {
            if(countDown!=null){
                countDown.await();
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
//        shutdown(singleThreadPool,countDown);
    }


    private static void submit(ExecutorService singleThreadPool,ThreadTask threadTask){
        try {
            singleThreadPool.submit(threadTask);
        }catch (Exception e){
            log.error("线程执行异常",e);
            throw new RuntimeException(e);
        }
    }


    public static void shutdown(ExecutorService singleThreadPool){
        if(singleThreadPool!=null&&!singleThreadPool.isShutdown()){
            singleThreadPool.shutdown();
        }
    }
}
